package com.example.lotterysystem.service.activitystatus;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.IActivityService;
import com.example.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.example.lotterysystem.service.operater.AbstractActivityOperator;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/2/3
 */
@Slf4j
@Component
public class ActivityStatusManagerImpl implements IActivityStatusManager {

    @Autowired
    private final Map<String, AbstractActivityOperator> operatorMap = new HashMap<>();

    @Resource
    private IActivityService activityService;

    //修改活动相关状态时存在依赖性，更新活动状态之前需要先更新活动奖品和人员状态
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        if (CollectionUtils.isEmpty(operatorMap)) {
            log.warn("当前operatorMap为空");
            return;

        }
        //避免修改operatorMap
        Map<String, AbstractActivityOperator> currMap = new HashMap<>(operatorMap);

        boolean update = false;
        //先处理人员，奖品
        update = processConvertStatus(convertActivityStatusDTO, currMap, 1);
        //后处理活动
        update = processConvertStatus(convertActivityStatusDTO, currMap, 2) || update;

        //更新缓存
        if (update) {
            activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
        }
    }

    @Override
    public void rollbackHandlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        //
        for (AbstractActivityOperator operator : operatorMap.values()){
            operator.convert(convertActivityStatusDTO);
        }
        //更新缓存
        activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
    }

    /**
     * 处理状态转化
     * @param convertActivityStatusDTO
     * @param currMap
     * @param sequence
     * @return
     */
    private boolean processConvertStatus(ConvertActivityStatusDTO convertActivityStatusDTO,
                                         Map<String, AbstractActivityOperator> currMap,
                                         int sequence) {
        boolean update = false;
        //遍历curMap
        Iterator<Map.Entry<String, AbstractActivityOperator>> iterator = currMap.entrySet().iterator();
        while (iterator.hasNext()) {
            AbstractActivityOperator operator = iterator.next().getValue();
            //判断operator是否需要转换
            if (operator.sequence() != sequence || !operator.needConvert(convertActivityStatusDTO)) {
                continue;
            }
            //转换
            if (!operator.convert(convertActivityStatusDTO)) {
                log.error("{},转换失败", operator.getClass().getName());
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_STATUS_CONVERT_ERROR);
            }
            //转换成功，删除当前 operator
            iterator.remove();
            update = true;
        }
        return update;
    }
}
